package service

import (
	"context"
	"distributed/registry"
	"fmt"
	"log"
	"net/http"
)

func Start(ctx context.Context, reg registry.Registration, host, port string,
	registerHandlersFunc func()) (context.Context, error) {

	registerHandlersFunc()
	ctx = startService(ctx, reg, host, port)
	err := registry.RegisterService(reg)
	if err != nil {
		return ctx, err
	}

	return ctx, nil
}

func startService(ctx context.Context, reg registry.Registration, host, port string) context.Context {
	ctx, cancel := context.WithCancel(ctx)

	var srv http.Server
	srv.Addr = host + ":" + port

	runServer(&srv, reg.ServiceName, cancel)

	runShutdownListener(ctx, reg.ServiceName, &srv, cancel)

	return ctx
}

func runServer(srv *http.Server, serviceName registry.ServiceName, cancel context.CancelFunc) {
	go func() {
		log.Println(srv.ListenAndServe())
		err := registry.ShutdownService(serviceName)
		if err != nil {
			log.Println(err)
		}
		cancel()
	}()
}

func runShutdownListener(ctx context.Context, serviceName registry.ServiceName, srv *http.Server,
	cancel context.CancelFunc) {
	go func() {
		fmt.Printf("%v started, press any key to stop.\n", serviceName)
		var s string
		fmt.Scanln(&s)

		err := registry.ShutdownService(serviceName)
		if err != nil {
			log.Println(err)
		}

		srv.Shutdown(ctx)
		cancel()
	}()
}
